package com.zcc.makingfriend.service.impl;

import com.zcc.makingfriend.dao.Article;
import com.zcc.makingfriend.dao.Message;
import com.zcc.makingfriend.dao.User;
import com.zcc.makingfriend.dto.MessageDto;
import com.zcc.makingfriend.mapper.ArticleMapper;
import com.zcc.makingfriend.mapper.MessageMapper;
import com.zcc.makingfriend.mapper.UserMapper;
import com.zcc.makingfriend.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zcc
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    MessageMapper messageMapper;

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public int addMessage(Message message) {
        message.setIsRead(0);
        message.setCreated(LocalDateTime.now());
        int i = 0;
        if (message.getReport() == 0) {
            i = articleMapper.deleteArticleById(message.getArticleId());
        } else {
            i = articleMapper.recoverReportArticle(message.getArticleId());
        }
        int j = messageMapper.addMessage(message);
        return( i ==1 && j == 1) ? 1: 0;
    }

    @Override
    public int readMessage(Long id) {
        return messageMapper.readMessage(id);
    }

    @Override
    public Long countUnread(Long toId) {
        return messageMapper.countUnread(toId);
    }

    @Override
    public List<MessageDto> findMessage(Long toId) {
        List<Message> message = messageMapper.findMessage(toId);
        List<MessageDto> messageDtos = new ArrayList<>();
        for (Message m: message) {
            Article article = articleMapper.getArticleById(m.getArticleId());
            User fromUser = userMapper.findUserById(m.getFromId());
            User toUser = userMapper.findUserById(m.getToId());
            MessageDto messageDto = new MessageDto(m, article, fromUser, toUser);
            messageDtos.add(messageDto);
        }
        return messageDtos;
    }
}
